﻿using System;
using System.Collections.Generic;
using AhpilyServer.Concurrent;
using Protocol.Dto.Fight;

namespace PokerServer.Cache.Fight
{
    /// <summary>
    /// 战斗的缓存层
    /// </summary>
    public class FightCache
    {
        // Dictionary
        // 用户id 对应的 房间id

        // 房间id 对应的 房间模型对象
        private readonly Dictionary<int, FightRoom> idRoomDict = new Dictionary<int, FightRoom>();

        // 重用的房间的队列
        private readonly Queue<FightRoom> roomQueue = new Queue<FightRoom>();


        // Attribute
        // 房间的id
        private readonly ConcurrentInt id = new ConcurrentInt(-1);

        private Dictionary<int, int> UidRoomDict { get; } = new Dictionary<int, int>();


        public FightRoom CreateFightRoom(List<int> uidList)
        {
            FightRoom room;

            if (roomQueue.Count > 0)
            {
                room = roomQueue.Dequeue();
                room.Init(uidList);
            }
            else
            {
                room = new FightRoom(id.Add_Get(), uidList);
            }

            // 绑定映射关系
            foreach (int uid in uidList)
            {
                UidRoomDict.Add(uid, room.Id);
            }

            idRoomDict.Add(room.Id, room);

            return room;
        }


        /// <summary>
        /// 获取战斗房间
        /// </summary>
        /// <param name="roomId"></param>
        /// <returns></returns>
        /// <exception cref="Exception"></exception>
        private FightRoom GetRoomByRoomId(int roomId)
        {
            if (idRoomDict.ContainsKey(roomId) == false)
            {
                throw new Exception("不存在这个房间");
            }

            return idRoomDict[roomId];
        }

        public FightRoom GetRoomByUid(int uid)
        {
            if (UidRoomDict.ContainsKey(uid) == false)
            {
                throw new Exception("当前用户不在房间");
            }

            int roomId = UidRoomDict[uid];

            return GetRoomByRoomId(roomId);
        }


        public bool IsFighting(int userId)
        {
            return UidRoomDict.ContainsKey(userId);
        }

        public void DestroyRoom(FightRoom room)
        {
            idRoomDict.Remove(room.Id);

            foreach (PlayerDto playerDto in room.PlayerList)
            {
                UidRoomDict.Remove(playerDto.userId);
            }


            // 清空上一局的全部牌
            room.PlayerList.Clear();

            room.LeaveUIdList.Clear();

            room.TableCardList.Clear();

            // 从新洗牌
            room.LibraryModel.Init();

            // 放到重用对象队列
            roomQueue.Enqueue(room);
        }
    }
}